import { loginAPI, getUserInfoAPI } from '@/api/login'
import { Message } from 'element-ui'
import router from '@/router'

export default {
  namespaced: true,
  state: {
    token: '',
    userInfo: {}
  },
  mutations: {
    SETTOKEN (state, value) {
      state.token = value
    },
    SETUSERINFO (state, value) {
      state.userInfo = value
    },
    // 退出登录时，清空vuex
    CLEANDATA (state) {
      state.token = ''
      state.userInfo = {}
    }
  },
  actions: {
    async login (context, form) {
      const res = await loginAPI(form)
      // console.log(res)
      if (res.code === 202) {
        Message.error(res.message)
        return false
      } else {
        context.commit('SETTOKEN', res.data.token)
        return true
      }
    },
    // 获取用户信息
    async getUserInfo (context) {
      const res = await getUserInfoAPI()
      // console.log(res)
      if (res.code === 206) {
        context.commit('CLEANDATA')
        Message.error('用户信息失效，请重新登录')
        router.push('/login')
      }
      context.commit('SETUSERINFO', res.data)
    }
  }
}
